/**
*  
* @Function 邮件发送工具类 
* @ProjectName credit-data-platform 
* @PackageName com.py.credit.utils    
* @FileName EmailUtil.java    
* @Date 2018年12月12日上午10:37:13
* @Author Min DongXv
* @Copyright (c) 2018, 金电联行 All Rights Reserved.   
*   
*/  
package com.py.credit.utils;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.mail.internet.MimeMessage;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.util.CollectionUtils;

import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;

import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * 
 * @Function 邮件发送工具类
 * @ClassName EmailUtil
 * @Date 2018年12月12日 上午10:37:13
 * @Author Min DongXv
 * 
 */
@Component
public class EmailUtil implements InitializingBean {

	private static final String ENCODE = "UTF-8";

	private static final String NO_TO_EMAILADDRESS = "请添加收件人";

	private static final String EMAIL_FAIL = "邮件发送失败";


	private static String emailHost;


	private static int emailPort;


	private static String emailUserName;


	private static String emailPassword;


	private static String fromEmail;


	private static String fromName;

	private static String emailProtocol = "smtp";

	private static JavaMailSenderImpl sender = sender();

	private EmailUtil() {
	}

	/**
	 *
	 * @Function 初始化邮件发送配置
	 * @FileName EmailUtil.java
	 * @MethodName sender
	 * @return
	 * @Author Min DongXv
	 *
	 */
	public static JavaMailSenderImpl sender() {
		JavaMailSenderImpl jms = new JavaMailSenderImpl();

		Properties p = new Properties();
		p.setProperty("mail.smtp.timeout", "10000");
		p.setProperty("mail.smtp.auth", "true");
		jms.setJavaMailProperties(p);
		return jms;
	}

	/**
	 *
	 * @Function 给单个收件人发送文本邮件
	 * @FileName EmailUtil.java
	 * @MethodName sendTextMessage
	 * @param to
	 *            收件人
	 * @param content
	 *            内容
	 * @param subject
	 *            标题
	 * @return
	 * @Author Min DongXv
	 *
	 */
	public static RestServiceResult<String> sendTextMessage(String to, String subject, String content) {
		RestServiceResult<String> result = new RestServiceResult<>();
		MimeMessage mimeMessage = sender.createMimeMessage();
		try {
			MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, ENCODE);
			if (StringUtils.isBlank(to)) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg(NO_TO_EMAILADDRESS);
				return result;
			} else {
				messageHelper.setTo(to);
			}
			messageHelper.setFrom(fromEmail, fromName);
			messageHelper.setSubject(subject);
			messageHelper.setText(content);
			messageHelper.setSentDate(new Date());
			sender.send(mimeMessage);
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg(EMAIL_FAIL);
			ExceptionLogger.error("EmailUtil#sendTextMessage", EMAIL_FAIL + e.getMessage(), e);
			return result;
		}
		return result;
	}

	/**
	 *
	 * @Function 发送文本邮件
	 * @FileName EmailUtil.java
	 * @MethodName sendTextMessages
	 * @param to
	 *            收件人列表
	 * @param copy
	 *            抄送人列表
	 * @param content
	 *            内容
	 * @param subject
	 *            标题
	 * @return
	 * @Author Min DongXv
	 *
	 */
	public static RestServiceResult<String> sendTextMessages(List<String> to, List<String> copy, String subject,
			String content) {
		RestServiceResult<String> result = new RestServiceResult<>();
		MimeMessage mimeMessage = sender.createMimeMessage();
		try {
			MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, ENCODE);
			if (CollectionUtils.isEmpty(to)) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg(NO_TO_EMAILADDRESS);
				return result;
			} else {
				String[] toArr = to.toArray(new String[to.size()]);
				messageHelper.setTo(toArr);
			}
			if (!CollectionUtils.isEmpty(copy)) {
				String[] copyArr = copy.toArray(new String[copy.size()]);
				messageHelper.setCc(copyArr);
			}
			messageHelper.setFrom(fromEmail, fromName);
			messageHelper.setSubject(subject);
			messageHelper.setText(content);
			messageHelper.setSentDate(new Date());
			sender.send(mimeMessage);
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg(EMAIL_FAIL);
			ExceptionLogger.error("EmailUtil#sendTextMessages", "邮件发送失败:" + e.getMessage(), e);
			return result;
		}
		return result;
	}

	/**
	 *
	 * @Function 给单个收件人发送带html的邮件
	 * @FileName EmailUtil.java
	 * @MethodName sendHtmlMessage
	 * @param to
	 *            收件人
	 * @param content
	 *            内容
	 * @param subject
	 *            标题
	 * @return
	 * @Author Min DongXv
	 *
	 */
	public static RestServiceResult<String> sendHtmlMessage(String to, String subject, String content) {
		RestServiceResult<String> result = new RestServiceResult<>();
		MimeMessage mimeMessage = sender.createMimeMessage();
		try {
			MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, ENCODE);
			if (StringUtils.isBlank(to)) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg(NO_TO_EMAILADDRESS);
				return result;
			} else {
				messageHelper.setTo(to);
			}
			// 设置发件人别名
			messageHelper.setFrom(fromEmail, fromName);
			// 设置标题
			messageHelper.setSubject(subject);
			messageHelper.setSentDate(new Date());
			messageHelper.setText(content, true);
			sender.send(mimeMessage);
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg(EMAIL_FAIL);
			ExceptionLogger.error("EmailUtil#sendHtmlMessage", EMAIL_FAIL + e.getMessage(), e);
			return result;
		}
		return result;
	}

	/**
	 *
	 * @Function 给单个收件人发送带html的邮件
	 * @FileName EmailUtil.java
	 * @MethodName sendHtmlMessageByTemplate
	 * @param to
	 *            收件人
	 * @param content
	 *            内容
	 * @param subject
	 *            标题
	 * @param useTemplate
	 *            是否使用模板 true是 false否
	 * @param model
	 *            模板参数
	 * @param tmplateName
	 *            模板路径名称
	 * @return
	 * @Author Min DongXv
	 *
	 */
	public static RestServiceResult<String> sendHtmlMessageByTemplate(String to, String subject,
			Map<String, Object> model, String tmplateName) {
		RestServiceResult<String> result = new RestServiceResult<>();
		MimeMessage mimeMessage = sender.createMimeMessage();
		try {
			MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, ENCODE);
			if (StringUtils.isBlank(to)) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg(NO_TO_EMAILADDRESS);
				return result;
			} else {
				messageHelper.setTo(to);
			}
			// 设置发件人别名
			messageHelper.setFrom(fromEmail, fromName);
			// 设置标题
			messageHelper.setSubject(subject);
			messageHelper.setSentDate(new Date());
			// 使用模板
			if (CollectionUtils.isEmpty(model) || StringUtils.isBlank(tmplateName)) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("模板配置异常");
				return result;
			}
			Configuration configuration = new Configuration();
			configuration.setClassForTemplateLoading(EmailUtil.class, "/template");
			Template t = configuration.getTemplate(tmplateName, ENCODE);
			String text = FreeMarkerTemplateUtils.processTemplateIntoString(t, model);
			messageHelper.setText(text, true);
			sender.send(mimeMessage);
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg(EMAIL_FAIL);
			ExceptionLogger.error("EmailUtil#sendHtmlMessageByTemplate", EMAIL_FAIL + e.getMessage(), e);
			return result;
		}
		return result;
	}

	/**
	 *
	 * @Function 发送带html的邮件
	 * @FileName EmailUtil.java
	 * @MethodName sendHtmlMessages
	 * @param to
	 *            收件人列表
	 * @param copy
	 *            抄送人列表
	 * @param content
	 *            内容
	 * @param subject
	 *            标题
	 * @param useTemplate
	 *            是否使用模板 true是 false否
	 * @param model
	 *            模板参数
	 * @param tmplateName
	 *            模板路径
	 * @return
	 * @Author Min DongXv
	 *
	 */
	public static RestServiceResult<String> sendHtmlMessages(List<String> to, List<String> copy, String subject,
			String content, boolean useTemplate, Map<String, Object> model, String tmplateName) {
		RestServiceResult<String> result = new RestServiceResult<>();
		MimeMessage mimeMessage = sender.createMimeMessage();
		try {
			MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, ENCODE);
			if (CollectionUtils.isEmpty(to)) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg(NO_TO_EMAILADDRESS);
				return result;
			} else {
				String[] toArr = to.toArray(new String[to.size()]);
				messageHelper.setTo(toArr);
			}
			if (!CollectionUtils.isEmpty(copy)) {
				String[] copyArr = copy.toArray(new String[copy.size()]);
				messageHelper.setCc(copyArr);
			}
			messageHelper.setFrom(fromEmail, fromName);
			messageHelper.setSubject(subject);
			if (!useTemplate) {
				// 不使用模板
				messageHelper.setText(content, true);
			} else {
				// 使用模板
				if (CollectionUtils.isEmpty(model) || StringUtils.isBlank(tmplateName)) {
					result.setCode(RestServiceResult.CODE_UNKNOW);
					result.setMsg("模板配置异常");
					return result;
				}
				Configuration configuration = new Configuration();
				configuration.setClassForTemplateLoading(EmailUtil.class, "/template");
				Template t = configuration.getTemplate(tmplateName, ENCODE);
				String text = FreeMarkerTemplateUtils.processTemplateIntoString(t, model);
				messageHelper.setText(text, true);
			}
			messageHelper.setSentDate(new Date());
			sender.send(mimeMessage);
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg(EMAIL_FAIL);
			ExceptionLogger.error("EmailUtil#sendHtmlMessages", EMAIL_FAIL + e.getMessage(), e);
			return result;
		}
		return result;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		if (null == sender) {
			sender = sender();
		}
		sender.setHost(emailHost);
		sender.setPort(emailPort);
		sender.setUsername(emailUserName);
		sender.setPassword(emailPassword);
		sender.setProtocol(emailProtocol);
	}

	/**
	 * @param emailHost
	 *            the emailHost to set
	 */
	@Value("${emailHost}")
	public void setEmailHost(String host) {
		emailHost = host;
	}

	/**
	 * @param emailPort
	 *            the emailPort to set
	 */
	@Value("${emailPort}")
	public void setEmailPort(int port) {
		emailPort = port;
	}

	/**
	 * @param emailUserName
	 *            the emailUserName to set
	 */
	@Value("${emailUserName}")
	public void setEmailUserName(String userName) {
		emailUserName = userName;
	}

	/**
	 * @param emailPassword
	 *            the emailPassword to set
	 */
	@Value("${emailPassword}")
	public void setEmailPassword(String password) {
		emailPassword = password;
	}

	/**
	 * @param fromEmail
	 *            the fromEmail to set
	 */
	@Value("${fromEmail}")
	public void setFromEmail(String fEmail) {
		fromEmail = fEmail;
	}

	/**
	 * @param fromName
	 *            the fromName to set
	 */
	@Value("${fromName}")
	public void setFromName(String fName) {
		fromName = fName;
	}
}